package com.yingyi.system.service.impl;

import com.yingyi.basic.service.impl.BaseServiceImpl;
import com.yingyi.system.domain.DictionaryDetail;
import com.yingyi.system.domain.DictionaryType;
import com.yingyi.system.mapper.DictionaryDetailMapper;
import com.yingyi.system.mapper.DictionaryTypeMapper;
import com.yingyi.system.service.IDictionaryTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DictionaryTypeServiceImpl extends BaseServiceImpl<DictionaryType> implements IDictionaryTypeService {


    @Autowired
    private DictionaryDetailMapper dictionaryDetailMapper;
    /**
     * 关联外键删除：
     *  1 先删除所有关联的数据
     *  2 再删除记录本身
     *
     * @param id
     */
    @Override
    @Transactional
    public void delete(Long id) {

        List<DictionaryDetail> detailsToDelete = dictionaryDetailMapper.queryByTypesId(id);

        if (detailsToDelete != null && !detailsToDelete.isEmpty()) {

            //使用stream的map方法进行对象与id的映射，然后批量删除
            List<Long> ids = detailsToDelete.stream().map(d -> d.getId()).collect(Collectors.toList());
            if(!ids.isEmpty()){
                dictionaryDetailMapper.patchDelete(ids);
            }

        }

        // 再 删除作为外键关联的记录本身
        super.delete(id);
    }


    /**
     * 批量删除也要考虑外键关联的问题
     * 关联外键删除：
     *  1 先删除所有关联的数据
     *  2 再删除记录本身
     */
    @Override
    @Transactional
    public void patchDelete(List<Long> ids) {

        //存储查询的要删除的DictionaryDetail数据的集合
        List<DictionaryDetail> detailsToDelete = new ArrayList<>();

        for (Long id : ids) {
            List<DictionaryDetail> dataToDel = dictionaryDetailMapper.queryByTypesId(id);

            //所有数据都要保存到集合中，不能直接赋值，会覆盖之前的数据
            detailsToDelete.addAll(dataToDel);
        }


        if (detailsToDelete != null && !detailsToDelete.isEmpty()) {

            List<Long> idsToDelete = detailsToDelete.stream().map(d -> d.getId()).collect(Collectors.toList());

            dictionaryDetailMapper.patchDelete(idsToDelete);

        }

        super.patchDelete(ids);
    }

}
